const validate = {
	// 不为空
	required: obj => {
		return obj.value == undefined || obj.value == 0 || obj.value == '' ? false : true
	},

	// 必选
	choose: obj => {
		return obj.value.length > 0 ? true : false
	},

	// 手机号验证
	mobile: obj => {
		let checkMobile = /^1[3-9][0-9]\d{8}$/
		return checkMobile.test(obj.value)
	},

	// 密码长度为8到16位且必须包含大小写字母和数字
	password: obj => {
		let checkPassword = new RegExp("(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[a-zA-Z0-9]{8,16}")
		return checkPassword.test(obj.value)
	}
}

function getRuleName(ruleRow){
	let ruleName = ''
	let ruleValue
	let keys = Object.key(validate)
	for(let i in ruleRow){
		if(keys.includes(i)){
			ruleName = i
			ruleValue = ruleRow[i]
			break
		}
	}
	
	return ruleName == '' ? false : {ruleName: ruleName, ruleValue: ruleValue}
}

export function validate (rules, ruleForm){
	let result = {}
	for(let i in rules){
		let formItemValue = ruleForm[i]
		for(let j in rules[i]){
			let rule = getRuleName(rules[i][j])
			try{
				if(!rule){
					result = {
						field: i,
						message: '没有该规则'
					}
					throw JSON.stringify(result)
				}
			}catch (err){
				return JSON.parse(err)
			}
			
			let checked = validate[rule.ruleName]({value: formItemValue, ruleValue: ruleValue})
			try{
				if(!checked){
					result = {
						field: i,
						message: rules[i][j]['message']
					}
					throw JSON.stringify(result)
				}
			}catch(err){
				return JSON.parse(err)
			}
		}
	}
	
	return true
}
